<template>
  <div class="practice-container">
    <div class="practice-start" v-if="!practiceStarted" @click="startPractice">
      <base-button type="primary">开始练习</base-button>
    </div>
    <div class="questions" v-for="(item, index) in questions" :key="index" v-show="index === idx">
      <p>
        <span>{{ idx + 1 }}/{{ questions.length }}</span>
        <span class="text-primary">&nbsp{{
            item.type === 'choice' ? item.isMultiple ? '多选' : '单选' : item.type === 'short-answer' ? '简答题' : '填空题'
          }}&nbsp</span>
        <span>{{ item.name }}</span>
        <span class="text-danger" v-show="answerShow"> 答案：{{ item.answer }}</span>
      </p>
      <!--      <div style="height: 1rem;"></div>-->
      <div v-if="item.type === 'choice'">
        <div
          :class="val.checked ? 'bgc' : ''"
          v-for="val in item.option"
          :key="val.id"
          class="list"
          @click="handleClick(val)"
        >
          {{ val.letter }}. {{ val.name }}
        </div>
      </div>

      <textarea v-else-if="item.type === 'short-answer'" v-model="item.userAnswer" style="height: 7rem;"></textarea>
      <input v-else-if="item.type === 'fill-in'" v-model="item.userAnswer"/>
    </div>
    <div class="btns">
      <base-button @click="back()"
                   :style="idx === 0 ? 'background-color:#fffff;' : ''"
                   :disabled="idx === 0 ? true : false"
                   class="animation-on-hover" type="info">
        上一题
      </base-button>
      <base-button @click="next()"
                   :style="idx === questions.length - 1 ? 'background-color:#fffff;' : ''"
                   :disabled="idx === questions.length - 1 ? true : false"
                   class="animation-on-hover" type="info">
        下一题
      </base-button>
      <base-button @click="submit();submitAndShowAnswer()"
                   class="animation-on-hover" type="primary">
        提交
      </base-button>
      <!--      <base-button v-show="isShow"
                         @click="answerShow = true"
                         class="animation-on-hover" type="warning">
              查看答案
            </base-button>-->
      <base-button v-show="isShow"
                   @click="refreshQuestions()"
                   class="animation-on-hover" type="warning">
        再来一组
      </base-button>
    </div>
  </div>
</template>

<script>
import NotificationTemplate from "../pages/Notifications/NotificationTemplate.vue";
import {BaseAlert} from "../components/index";
import questionBaseData from "../assets/json/QuestionBase3.json";
import {baseURL} from "../axiosConfig";

const QUESTION_NUM = 5;

export default {
  components: {
    NotificationTemplate,
    BaseAlert,
  },
  data() {
    return {
      localUserId: 0,
      practiceStarted: false,
      idx: 0, // 当前题目索引
      allScore: 0, // 总分数
      isShow: false, // 是否显示查看答案按钮
      answerShow: false, // 是否显示答案
      isMultipleAnswer: [], // 多选题选项数组
      questions: [], // 存储随机选取的题目
      questionBase: questionBaseData, // 题库数据
      type: ["", "info", "success", "warning", "danger"], // 通知类型
      notifications: {
        topCenter: false,
      },
      startTime: 0,
      examResult: {
        questionId: [],
        answerTimes: [0,0,0,0,0],
        useTrueTimes: [],
        difficulty: [],
        questionTypes: [],
        result: [],
        score: [],
        userId: 0,
      },
      TDA: 0,
    };
  },
  created() {
    // 组件创建时获取随机题目
    this.questions = this.getQuestions(QUESTION_NUM);
  },
  methods: {
    submitAndShowAnswer() {
      // 这里执行提交的逻辑
      this.$emit('get-leida'); // 触发自定义事件
      this.answerShow = true; // 设置答案显示
    },
    startPractice() {
      this.practiceStarted = true;
      this.recordStartTime();
    },
    // 记录进入组件时的时间
    recordStartTime() {
      this.startTime = new Date().getTime();
    },

    // 清除计时器
    clearTimer() {
      this.startTime = 0;
    },

    // 显示通知
    notifyVue(verticalAlign, horizontalAlign, message) {
      const color = Math.floor(Math.random() * 4 + 1);
      this.$notify({
        component: NotificationTemplate,
        icon: "tim-icons icon-bell-55",
        horizontalAlign: horizontalAlign,
        verticalAlign: verticalAlign,
        message: message,
        type: this.type[color],
        timeout: 5000,
      });
    },

    // 获取随机题目
    getQuestions(numQuestions) {
      const selectedQuestions = [];
      const selectedIndexes = new Set();

      while (selectedIndexes.size < numQuestions) {
        const randomIndex = Math.floor(Math.random() * this.questionBase.length);
        if (!selectedIndexes.has(randomIndex)) {
          selectedIndexes.add(randomIndex);
          const question = {...this.questionBase[randomIndex]};
          question.isOk = false; // 初始化题目的正确与否为false
          question.userAnswer = ""; // 初始化用户答案为空字符串
          question.checked = false;
          selectedQuestions.push(question);
        }
      }

      return selectedQuestions;
    },

    // 进入下一题
    next() {
      // 计算答题时间并保存
      if (this.startTime !== 0) {
        const endTime = new Date().getTime();
        const answerTime = endTime - this.startTime;
        this.examResult.useTrueTimes[this.idx] = answerTime;
        this.examResult.answerTimes[this.idx] = this.quantizeAnswerTime(answerTime);
        this.clearTimer(); // 重置开始时间
        this.recordStartTime();
      }
      this.idx++;
    },

    // 返回上一题
    back() {
      // 计算答题时间并保存
      if (this.startTime !== 0) {
        const endTime = new Date().getTime();
        const answerTime = endTime - this.startTime;
        this.examResult.useTrueTimes[this.idx] = answerTime;
        this.examResult.answerTimes[this.idx] = this.quantizeAnswerTime(answerTime);
        this.clearTimer(); // 重置开始时间
        this.recordStartTime();
      }
      this.idx--;
    },

    // 点击选项
    handleClick(info) {
      const question = this.questions[this.idx];
      const option = question.option;

      option.forEach((item) => {
        if (item.id === info.id) {
          item.checked = !item.checked;
        } else if (!question.isMultiple) {
          item.checked = false;
        }
      });

      let isAnswer = info.letter;
      const answer = question.answer;

      if (question.isMultiple) {
        this.isMultipleAnswer = [];
        option.forEach((item) => {
          if (item.checked) {
            this.isMultipleAnswer.push(item.letter);
          }
        });
        isAnswer = this.isMultipleAnswer.join("");
      }

      console.log("选中的答案", isAnswer);

      if (isAnswer === answer) {
        question.isOk = true;
      } else {
        question.isOk = false;
      }

      question.userAnswer = isAnswer; // 保存用户的答案
    },

    // 提交答案
    submit() {
      this.allScore = 0;
      this.examResult.result = [];
      this.questions.forEach((item) => {
        let isTrue = false;

        if (item.type === "choice" && item.option) {
          // 处理选择题
          const userAnswers = item.option
            .filter((o) => o.checked)
            .map((o) => o.letter)
            .join(",");
          isTrue = userAnswers === item.answer;
        } else if (item.type === "fill-in") {
          // 处理填空题，要求完全一致
          isTrue = item.userAnswer === item.answer;
        } else if (item.type === "short-answer") {
          // 处理简答题，仅需包含关键字符串
          isTrue = item.keywords.every((keyword) =>
            item.userAnswer.includes(keyword)
          );
        }

        if (isTrue) {
          this.allScore += item.score;
        }
        this.examResult.result.push(isTrue); // 保存每道题目的正确与否
      });

      // 计算最后一题的答题时间
      if (this.startTime !== 0) {
        const endTime = new Date().getTime();
        const answerTime = endTime - this.startTime;
        this.examResult.useTrueTimes[this.idx] = answerTime;
        this.examResult.answerTimes[this.idx] = this.quantizeAnswerTime(answerTime);
        this.clearTimer(); // 重置开始时间
      }

      // 计算每道题目的难度系数、题目类型和分数
      this.questions.forEach((item) => {
        this.examResult.questionId.push(item.id)
        this.examResult.difficulty.push(item.difficulty);
        this.examResult.questionTypes.push(0);
        this.examResult.score.push(item.score);
      });
      this.examResult.userId = this.localUserId;

      console.log("题目id：" + this.examResult.questionId);
      console.log("题目用时：" + this.examResult.useTrueTimes);
      console.log("难度系数：" + this.examResult.difficulty);
      console.log("题目类型：" + this.examResult.questionTypes);
      console.log("每道题目的正确与否：" + this.examResult.result);
      console.log("每道题目的得分：" + this.examResult.score);

      // 检查是否所有题目都已作答
      if (this.examResult.result.length < this.questions.length) {
        this.notifyVue("top", "center", "还有题目未作答");
        return;
      }

      this.TDA = this.calcTDA(this.examResult.result, this.examResult.answerTimes, this.examResult.difficulty, this.examResult.score);

      setTimeout(() => {
        // 在使用TDA之前进行有效性检查
        if (!isNaN(this.TDA)) {
          this.notifyVue("top", "center", `本次获得TDA：` + this.TDA);
        } else {
          // 如果TDA为NaN，给它赋予一个默认值，或者采取其他处理方式
          this.TDA = this.calcTDA(this.examResult.result, this.examResult.answerTimes, this.examResult.difficulty, this.examResult.score); // 给TDA赋予默认值
          this.notifyVue("top", "center", `本次获得TDA：` + this.TDA);

          // 提交TDA结果到后端
          this.submitTDA();
        }
        this.isShow = true; // 显示查看答案按钮
      }, 100);

      this.$axios.post(baseURL + ':8080/student/tda/submitExamResult',
        this.examResult)
        .then(response => {
          console.log(response.data);
        })
        .catch(error => {
          console.error('提交练习结果时出错:', error);
        });
    },

    // 发起axios请求
    submitTDA() {
      const params = new URLSearchParams(); // 创建URLSearchParams对象

      // let courseId;
      // courseId = this.$route.params.id;

      // 添加多个参数
      // params.append('course_id', courseId);
      params.append('tda', this.TDA);

      const url = baseURL + ':8080/student/tda/submitTDAResult?' + params.toString(); // 构建请求URL
      this.$axios.post(url)
        .then(response => {
          // 处理响应数据
          console.log(response.data);
        })
        .catch(error => {
          // 处理错误
          console.error('提交TDA数据时出错：', error);
        });
    },

// 刷新题目
    refreshQuestions() {
      this.questions = this.getQuestions(QUESTION_NUM);
      this.isShow = false;
      this.idx = 0;
      this.answerShow = false;
      this.examResult.questionId = new Array(QUESTION_NUM).fill(0); // 重置题目ID数组
      this.examResult.answerTimes = new Array(QUESTION_NUM).fill(0); // 重置答题时间数组
      this.examResult.difficulty = new Array(QUESTION_NUM).fill(0); // 重置难度系数数组
      this.examResult.questionTypes = new Array(QUESTION_NUM).fill(""); // 重置题目类型数组
      this.examResult.score = new Array(QUESTION_NUM).fill(0); // 重置分数数组
      this.examResult.result = new Array(QUESTION_NUM).fill(""); // 重置正确与否数组
      this.examResult.useTrueTimes = new Array(QUESTION_NUM).fill(0); // 重置答题真实时间数组

      // 清空选择题中的 checked 值
      this.questions.forEach(question => {
        if (question.type === "choice") {
          question.option.forEach(option => {
            option.checked = false;
          });
        }
      });
    }
    ,


// 将答题时间量化
    quantizeAnswerTime(time) {
      if (time <= 7000) {
        return 0.1;
      } else if (time > 7000 && time <= 15000) {
        return 0.3;
      } else {
        return 0.5;
      }
    }
    ,

// 将答案是否正确量化
    quantizeResult(result) {
      var quantizedResult = [];
      for (var i = 0; i < result.length; i++) {
        quantizedResult.push(result[i] ? 1 : 0);
      }
      return quantizedResult;
    }
    ,

    calcTDA(result, answerTimes, difficulty, score) {
      result = this.quantizeResult(result);
      var sum = 0;
      for (var i = 0; i < result.length; i++) {
        sum += (result[i] + result[i] * (-answerTimes[i] + difficulty[i] * score[i]));
      }
      var TDA = sum / result.length;
      TDA = (TDA * 10).toFixed(2);
      console.log("TDA:" + TDA)
      this.$store.state.TDA = TDA;  //修改值
      console.log("已修改TDA:" + this.$store.state.TDA);
      return TDA;
    }
  },
  mounted() {
    // 当组件挂载时，从 localStorage 读取 userId
    this.localUserId = localStorage.getItem('userId') || 123456;
    // this.examResult.userId = this.localUserId;
    console.log("Exam-userId:"+this.localUserId)
  }
};
</script>

<style scoped>
.practice-start {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(255, 255, 255, 0.71); /* 半透明白色背景 */
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9; /* 确保遮罩层位于最顶层 */
  color: white;
}

* {
  padding: 0;
  box-sizing: border-box;
}

.btns {
  position: absolute; /* 设置绝对定位 */
  bottom: 1rem; /* 定位到底部 */
  width: 100%; /* 可选，根据需要设置 */
}

.questions {
  width: auto;
  padding: 10px;
  color: rgb(81, 81, 82);
  font-size: 12px;
}

button {
  margin-top: 15px;
  margin-left: 1rem !important;
  margin-right: 10px;
  outline: none;
  background-color: rgb(33, 157, 248);
  border: 0;
  padding: 10px;
  font-weight: 500 !important;
}

button:active {
  background-color: rgb(44, 60, 66);
}

.list {
  margin-top: 5px;
  padding: 7px 5px;
  font-size: 16px;
}

.bgc {
  color: #FFFFFF;
  background-color: #419EF9;
}

.answer {
  color: #E14ECA;
  font-size: 16px;
  margin-left: 20px;
}

.questions p span {
  font-size: 16px;
  font-weight: 400;
}

/* 新增输入框样式 */
input, textarea {
  width: calc(100% - 30px); /* 宽度占满可用空间 */
  padding: 8px; /* 内边距 */
  margin-left: 0 !important;
  margin-top: 1.5rem; /* 与问题描述的间距 */
  box-sizing: border-box; /* 盒模型 */
  border: 2px solid rgb(180, 176, 176); /* 边框颜色与按钮颜色一致 */
  border-radius: 5px; /* 圆角边框 */
  font-size: 16px; /* 字体大小 */
  color: rgb(81, 81, 82); /* 字体颜色 */
  position: absolute; /* 设置绝对定位 */
  bottom: 5rem; /* 定位到底部 */
  left: 15px;
  resize: none;
}

input:focus, textarea:focus {
  border-color: #419EF9; /* 聚焦时边框颜色 */
  outline: none; /* 移除默认聚焦轮廓 */
}
</style>
